﻿using System;
using System.Web.Mvc;
using Actya.Core.Infrastructure;

namespace Actya.Web.Mvc
{
	public abstract class CmsWebViewPage<TModel> : WebViewPage<TModel>
	{
		public CmsHelper<TModel> Cms { get; set; }
		public ICmsContext CmsContext { get; set; }

		public override void InitHelpers()
		{
			base.InitHelpers();
			// UGLY HACK: Layout pages aren't instantiated via the container, so the dependencies are not set.
			// We have to store the CmsContext somewhere so the layout page can access it.
			if (this.CmsContext != null)
			{
				// We're dealing with a normal view page that has the CmsContext set properly by the container.
				Cms = new CmsHelper<TModel>(base.ViewContext, this, this.CmsContext, this.Html);
				ViewBag.CmsContext = this.CmsContext;
			}
			else
			{
				// We're probably in the layout. 
				if (ViewBag.CmsContext == null)
				{
					//throw new NullReferenceException("There is no way to obtain the current CmsContext. We can't continue.");
				}
				Cms = new CmsHelper<TModel>(base.ViewContext, this, ViewBag.CmsContext, this.Html);
			}
		}
	}
}
